import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { BaseService } from './base.service';
import { UserService } from './user.service';
import { catchError, timeout } from 'rxjs/operators';
import { environment } from '../../environments/environment';
import { Observable } from 'rxjs';
import qs from 'qs';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    signature: '',
    os: '3',
    imei: '',
    timestamp: '',
    Authorization: '',
    osVersion: '',
    'Cache-Control': 'no-cache',
  }),
};

@Injectable({
  providedIn: 'root',
})
export class HttpsObService implements Global.HTTPS {
  public baseUrl: string = ''; /* 路径前缀 */
  public platform: Global.Platforms;

  constructor(
    private http: HttpClient,
    private baseService: BaseService,
    private userService: UserService
  ) {
    // 获取 pc/mobile
    const isPC = this.userService.getIsPc();
    this.platform = isPC ? 'pc' : 'mobile';
    this.baseUrl = isPC ? environment.baseUrlPc : environment.baseUrl;
    console.log('=>', '是否pc', isPC, 'BASEURL', this.baseUrl);
  }

  /**
   * @description: 生成额外的请求头参数
   */
  createExtraHeaders() {
    const timestamp = new Date().getTime();
    const imei = this.baseService.getImei().toString();
    const signature = this.baseService.getMd5NcodeAPP(timestamp);
    const token = this.baseService.getUserToken();
    const osVersion = this.baseService.getBrowserVersion();
    return {
      imei,
      timestamp: String(timestamp),
      signature,
      token,
      osVersion,
    } as Global.IHeaderParams;
  }
  /**
   * @param isParams 是否get的params
   * @param extra 额外参数
   * @description: 生成额外的请求参数
   */
  createExtraParams(extra = {}) {
    return qs.stringify(extra);
  }

  /**
   * @param url
   * @param params
   * @param extra eg:   {pc:{id:1},mobile:{id:2}}
   * @description: GET
   */
  get<T = any>(
    url: string,
    params: Record<string, any>,
    extra?: Global.IExtraPlatformParmas
  ): Observable<Global.IResponse<T>> {
    const extraHeaders = this.createExtraHeaders();
    Object.entries(extraHeaders).forEach(([key, value]) =>
      httpOptions.headers.set(key, value)
    );
    const extraParams = (extra && extra[this.platform]) || {};
    return this.http
      .get<Global.IResponse<T>>(
        `${this.baseUrl}${url}${
          '?' + qs.stringify({ ...params, ...extraParams })
        }`,
        httpOptions
      )
      .pipe(timeout(80000))
      .pipe(
        catchError((err) => {
          throw err;
        })
      );
  }

  /**
   * @param url
   * @param data
   * @param extra
   * @description: POST
   */
  post<T>(
    url: string,
    data: Record<string, any>,
    extra?: Global.IExtraPlatformParmas
  ): Observable<Global.IResponse<T>> {
    const extraHeaders = this.createExtraHeaders();
    Object.entries(extraHeaders).forEach(([key, value]) =>
      httpOptions.headers.set(key, value)
    );
    const extraData = (extra && extra[this.platform]) || {};
    return this.http
      .post<Global.IResponse<T>>(
        `${this.baseUrl}${url}`,
        { ...data, ...extraData },
        httpOptions
      )
      .pipe(timeout(80000))
      .pipe(
        catchError((err) => {
          throw err;
        })
      );
  }
}
